package com.mdinic.blogovi.service;

import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.mdinic.blogovi.model.BlogPost;
import com.mdinic.blogovi.model.Promote;

@Service
public class Scheduler {

    private static final String SPACE = " ";

    private static final Logger LOG = Logger.getLogger(Scheduler.class);

    private final BlogPost blogPost = new BlogPost();

    @Scheduled(fixedRate = DateUtils.MILLIS_PER_MINUTE * 5)
    public void promote() {
        StringBuilder sb = new StringBuilder();
        List<Promote> findAllPromotes = Promote.findAllPromotes();
        if (findAllPromotes.isEmpty()) {
            LOG.info("No promote rules found. Promotion will not be performed.");
            return;
        }
        for (Promote promote : findAllPromotes) {
            sb.append(promote.getExpression());
            sb.append(SPACE);
        }
        blogPost.promoteWithThisCondition(sb.toString());
    }

}
